package controller

import (
	"blog_server/model"
	"blog_server/utils"
	"github.com/gin-gonic/gin"
)

func GetCategoryList(c *gin.Context) {
	db := model.GetDB()
	var Categories []model.Category

	if err := db.Find(&Categories).Error; err != nil {
		utils.Fail(c, nil)
		return
	}

	utils.Success(c, gin.H{"categories": Categories})
}

func GetCategory(c *gin.Context) {
	db := model.GetDB()
	var Category model.Category

	if err := db.Where("id = ?", c.Param("id")).Find(&Category).Error; err != nil {
		utils.Fail(c, nil)
		return
	}

	utils.Success(c, gin.H{"categoryName": Category.CategoryName})
}

func CreateCategory(c *gin.Context) {
	db := model.GetDB()
	var requestCategory model.CategoryRequest

	if err := c.ShouldBind(&requestCategory); err != nil {
		utils.Fail(c, nil)
	}

	var Category model.Category
	db.Where("name = ?", requestCategory.CategoryName).First(&Category)
	if Category.ID == 0 {
		utils.Fail(c, nil)
		return
	}

	newCategory := model.Category{
		CategoryName: requestCategory.CategoryName,
	}

	db.Create(&newCategory)

	utils.Success(c, nil)
}

func UpdateCategory(c *gin.Context) {
	db := model.GetDB()
	categoryId := c.Param("id")
	var requestCategory model.CategoryRequest

	if err := c.ShouldBind(&requestCategory); err != nil {
		utils.Fail(c, nil)
		return
	}

	var Category model.Category

	if err := db.Where("id = ?", categoryId).First(&Category).Error; err != nil {
		utils.Fail(c, nil)
	}

	db.Model(&Category).Update("category_name", requestCategory.CategoryName)

	utils.Success(c, nil)
}

func DeleteCategory(c *gin.Context) {
	db := model.GetDB()
	categoryId := c.Param("id")

	var category model.Category
	if err := db.Where("id = ?", categoryId).First(&category).Error; err != nil {
		utils.Fail(c, nil)
	}

	var articles []model.Article
	db.Model(&model.Article{}).Where("category_id = ?", categoryId).Find(&articles)
	db.Model(&articles).Update("category_id", 0)
	db.Delete(&category)

	utils.Success(c, nil)
}
